import Vue from 'vue'
import VueRouter from 'vue-router'
import instance from '@/utils/request';

Vue.use(VueRouter)

const routes = [
  {
    path:'/',
    redirect: '/index'
  },
  {
    path: '/login',
    name: 'Login',
    component: ()=>import('@/views/Login.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: ()=>import('@/views/Register.vue')
  },
  {
    path: '/index',
    name: 'Index',
    //redirect:'/index/list',
    component: ()=>import('@/views/Index.vue'),
    // 嵌套路由
    children: [{
      path: "",
      component: ()=>import('@/views/home/Home.vue')
    },{
      path: 'list',
      component: ()=>import('@/views/koubei/List.vue')
    },{
      path: 'add',
      component: ()=>import('@/views/koubei/Add.vue')
    }]
  },

]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 路由全局前置守卫
/*
to 路由去的地方
from 路由从哪里来
next() ：放行 如果没有next()就不会继续路由跳转了 停止了
*/ 

router.beforeEach((to,from,next)=>{
  console.log("beforeEach.............");
  console.log(to,from);
  // 1. 如果要进入登陆页面或者进入注册页面 直接放行
  if(to.path === "/login" || to.path === "/register"){
    next();
  }else {
    // 2.验证token
    instance
    .get('http://localhost:8080/elemrg/admin/verifyToken')
    .then((res)=>{
      console.log(res);
      // 1.token正确
      if(res.data.code === 0){
        next();
      }else if (res.data.code === 1) {
        // 2.token不存在 返回到登录界面
        router.push("/login")
      }else if (res.data.code === 2) {
        //3.token过期 
        // 先把过期的token删除 然后再跳转涛登录界面
        localStorage.removeItem("token")
        router.push("/login")
      }
    })
    .catch((err)=>{
      console.error(err);
    })
  }


  // 
})

export default router
